package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.kh.getProperty;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import net.sf.json.JSONObject;
import java.time.Instant;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;

public class dingding implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(dingding.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
		def outData;
        //try {
			//查询待发送的任务
            List message_flag = eliteBean.chaxun_sql("select message_url,message_type from hst_senddingmessage where message_flag = '0' order by createdate limit 1", "dataSource");
			if(message_flag.size()==0){
				log.debug("无消息");
				return 1;
			}
			def message_url = message_flag.get(0).get("message_url").toString();
			def message_type = message_flag.get(0).get("message_type").toString();
			log.debug("message_url：" + message_url);
			log.debug("message_type：" + message_type);
			def guid = Util.getGuid();
			//任务打标
            def updatesql = "update hst_senddingmessage set message_flag = '"+guid+"' where message_url = '"+message_url+"' and message_type = '"+message_type+"' and message_flag = '0' limit 10";
            def updatesqlresult = eliteBean.update(updatesql, "dataSource");
			
			//处理标记的数据
			List message = eliteBean.chaxun_sql("select group_concat(s1.mobile SEPARATOR ',') mobile,group_concat(s1.staffname SEPARATOR ',') staff1,group_concat(concat('@',s1.staffname) SEPARATOR ' ') staff,concat(workorderno,'、',workordertype,'、',node_name,'、','创建人:',s.staffname,' ','\\n') body from hst_senddingmessage h left join staff s1 on find_in_set(s1.staff_id,h.staffids) ,staff s where  s.staff_id = h.createby and message_flag = '"+guid+"' group by h.workorderno,h.message_type", "dataSource");
			
			//def staff = message.get(0).get("staff").toString();
			//def body = message.get(0).get("body").toString();
			//log.debug("staff：" + staff);
			//log.debug("body：" + body);
			
			def message_body = "";
			def message_staff = "";
			def message_staff1 = "";
			def message_mobile = "";
			int num = 0;
			for(int i=0;i<message.size();i++){
				//循环拼接@人名
				message_staff = message_staff +message.get(i).get("staff").toString() + ' ';
				//循环拼接人名
				message_staff1 = message_staff1 +message.get(i).get("staff1").toString() + ',';
				//循环拼接手机
				message_mobile = message_mobile +message.get(i).get("mobile").toString() + ',';
				//手机为空的替换掉
				message_mobile = message_mobile.replace(",,", ",");
				//本次通知任务数量
				num = i+1
				//拼接message_body
				message_body = message_body + '- ' + num + " " + message.get(i).get("body").toString();
			}
			log.debug("message_body：" + message_body);

			log.debug("message_staff：" + message_staff);
			
			log.debug("message_staff1：" + message_staff1);
			
			log.debug("message_mobile：" + message_mobile);
			
			message_mobile = message_mobile.split(",");
			log.debug("message_mobile：" + message_mobile);
			
			//人名去重
			//将字符串变成数组，然后利用stream流变成集合
			List<String> throughLines = Arrays.stream(message_staff1.split(",")).collect(Collectors.toList());
			//利用stream流将集合去重
			List<String> throughLineList = throughLines.stream().distinct().collect(Collectors.toList());
			//然后再用Stringuitls.join将集合变成逗号分开的字符串
			String thoughLineTarget = StringUtils.join(throughLineList, ",");
			log.debug("thoughLineTarget：" + thoughLineTarget);
			
			//处理人数量字符串长度
			int len1 = thoughLineTarget.length();
			//替换逗号处理人数量字符串长度
			int len2 = thoughLineTarget.replace(",", "").length();
			//本次通知人数
			int len = len1 - len2 + 1;
			log.debug("本次通知人数:"+len);

			def text = "#### 工单提醒  \n > 本次工单处理人" + message_staff + " \n" + message_body;
			log.debug("text：" + text);
			
			log.debug("-------------------------开始调用钉钉通知接口-------------------------");
			def timeout=10000;
			def enablessLfag=0;
			def charset="utf-8";
			Map maps =new HashMap();
			maps.put("Content-Type","application/json;charset=utf-8");
			def url = message_url;
			//body
			JSONObject  bodys = new JSONObject();
			bodys.put("msgtype", "markdown");
			JSONObject markdown = new JSONObject();
			//markdown.put("title", "【工单提醒】 本次一共" + num + "个工单");
			markdown.put("title", "【过河兵工单提醒】");
			markdown.put("text", text);
			JSONObject at = new JSONObject();
			at.put("atMobiles",message_mobile);
			if(len>6){
				at.put("isAtAll",true);
			} else {
				at.put("isAtAll",false);
			}
			
			
			bodys.put("markdown", markdown);
			bodys.put("at", at);
			
			//JSONObject json = new JSONObject(bodys);
			log.debug("这是body："+bodys);
			
			def result=Util.doHttpPostUseHead(url, bodys.toString(), charset, timeout, enablessLfag, maps );
			log.debug("这是json："+result);
			//JSONObject resultObject = JSONObject.fromObject(result);

            outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
        //} catch (Exception e) {
        //    log.error("接口处理异常" + e.getMessage());
        //    outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        //}

        log.debug("发送钉钉消息 信息完成返回结果:" + result);

        return result;
    }

}
